package com.woniu.zsd.recycle.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniu.zsd.recycle.mapper.MaterialTypeMapper;
import com.woniu.zsd.recycle.mapper.WastePricingMapper;
import com.woniu.zsd.recycle.model.MaterialType;
import com.woniu.zsd.recycle.model.RecyclingRecord;
import com.woniu.zsd.recycle.mapper.RecyclingRecordMapper;
import com.woniu.zsd.recycle.model.WastePricing;
import com.woniu.zsd.recycle.param.StoreParam;
import com.woniu.zsd.recycle.service.RecyclingRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 彭于晏
 * @since 2025年02月18日
 */
@Service
public class RecyclingRecordServiceImpl extends ServiceImpl<RecyclingRecordMapper, RecyclingRecord> implements RecyclingRecordService {
    @Resource
    private RecyclingRecordMapper recyclingRecordMapper;
    @Resource
    private MaterialTypeMapper materialTypeMapper;
    @Resource
    private WastePricingMapper wastePricingMapper;
    @Resource
    private RedissonClient redissonClient;
    @Override
    public void store(StoreParam param) throws Exception {
        MaterialType materialType = materialTypeMapper.selectById(param.getMaterialTypeId());
        if (materialType == null) {
            throw new Exception("该废品类型不存在");
        }
        String typeName = materialType.getTypeName();
        QueryWrapper<WastePricing> wrapper = new QueryWrapper<>();
        wrapper.eq("material_type_id",param.getMaterialTypeId());
        wrapper.eq("site_id",param.getStationId());
        WastePricing wastePricing = wastePricingMapper.selectOne(wrapper);
        if (wastePricing == null) {
            throw new Exception("该站点未配置该废品的单价");
        }
        RLock lock = redissonClient.getFairLock("lock");
        try {
            lock.lock();
            RecyclingRecord recyclingRecord = new RecyclingRecord();
            recyclingRecord.setStationId(param.getStationId());
            recyclingRecord.setMaterialType(typeName);
            recyclingRecord.setUnit(wastePricing.getUnit());
            recyclingRecord.setAmount(param.getAmount());
            recyclingRecord.setUpdatedAt(LocalDateTime.now());
            recyclingRecord.setDeliverName(param.getDeliverName());
            recyclingRecord.setDeliverPhone(param.getDeliverPhone());
            recyclingRecordMapper.insert(recyclingRecord);
        }finally {
            lock.unlock();
        }
    }
}
